<?php
namespace app\h5api\controller;

use app\common\model\CouponReceive;
use app\common\model\DataProvince;

class Coupon extends Base
{

    /**
     * @route('h5/GetCouponList')
     * 获取优惠券列表
     */
    public function GetCouponList()
    {
        $model = new \app\common\model\Coupon();
        $coupons = $model->get_coupon_list($this->_userid,$this->limit);
        $this->result($coupons,1,'返回成功');
    }

    /**
     * @route('h5/UserGetCoupon')
     * 用户领取消费券
     */
    public function UserGetCoupon()
    {
        $model = new \app\common\model\Coupon();
        $gmodel = new CouponReceive();
//        $model->edit2(["status"=>2],["coupon_number"=>0]);
        $couponid = input('coupon_id');
        $cwhere = [
            ["coupon_id",'=',$couponid],
//            ['coupon_number','>',0],
            ["status",'=',1],
            ["is_del",'=',1],
        ];
        $coupon = $model->getOne($cwhere,'*',true);
        if(!$coupon){
            $this->result('',-1,'不存在该可领取消费券');
        }
        if($coupon['coupon_number'] <= 0){
            $this->result('',-1,'该消费券已被领光，请明天再来吧！');
        }
        $mywhere = [
            ["coupon_id",'=',$couponid],
            ["user_id","=",$this->_userid],
            ["is_use","in",[1,2]],
        ];
        $mycoupon = $gmodel->getOne($mywhere);
        if($mycoupon){
            $this->result('',-1,'您已领取过该消费券');
        }
        $data = [
            "coupon_id" => $coupon['coupon_id'],
            "coupon_name" => $coupon['coupon_name'],
            "discount" => $coupon['discount'],
            "fullmoney" => $coupon['fullmoney'],
            "use_stime" => $coupon['send_stime'],
            "use_etime" => $coupon['send_etime'],
            "user_id" => $this->_userid,
            "type" => 2,
        ];
        $gmodel->startTrans();
        $rs = $gmodel->edit($data);
//        消费券数量减一
        $result = $model->decsum(['coupon_id' => $couponid]);
        if(!$result){
            $gmodel->rollback();
            $this->result('',-1,'领取失败');
        }
        if(!$rs){
            $gmodel->rollback();
            $this->result('',-1,'领取失败');
        }
        $gmodel->commit();
        $this->result('',1,'领取成功');
    }

    /**
     * @route('h5/UserCouponList')
     * 获取用户优惠券列表
     */
    public function UserCouponList()
    {
        $model = new CouponReceive();
        $coupons = $model->user_coupon_list($this->_userid,$this->limit);
        $this->result($coupons,1,'返回成功');
    }
}
